package com.neuedu.his.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neuedu.his.po.Checkapply;
import com.neuedu.his.po.Fmeditem;
import com.neuedu.his.po.Department;
import com.neuedu.his.service.CheckapplyService;
import com.neuedu.his.service.FmeditemService;
import com.neuedu.his.service.DepartmentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/api/test-items")
public class CheckapplyController {

    private static final Logger log = LoggerFactory.getLogger(CheckapplyController.class);

    @Autowired
    private FmeditemService fmeditemService;

    @Autowired
    private CheckapplyService checkapplyService;

    @Autowired
    private DepartmentService departmentService;

    /**
     * 获取所有检验项目
     */
    @GetMapping
    public ResponseEntity<List<Fmeditem>> getTestItems() {
        try {
            log.info("开始查询所有检验项目");
            QueryWrapper<Fmeditem> wrapper = new QueryWrapper<>();
            wrapper.ne("DelMark", 1)
                    .eq("RecordType", 2); // 假设RecordType=2表示检验项目

            List<Fmeditem> items = fmeditemService.list(wrapper);
            log.info("获取检验项目成功，数量={}", items.size());
            return ResponseEntity.ok(items);
        } catch (Exception e) {
            log.error("获取检验项目异常", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 搜索检验项目（按名称）
     */
    @GetMapping("/search")
    public ResponseEntity<List<Fmeditem>> searchTestItems(@RequestParam String keyword) {
        try {
            if (keyword == null || keyword.trim().isEmpty()) {
                log.warn("搜索检验项目失败：关键词为空");
                return ResponseEntity.badRequest().build();
            }

            String trimmedKeyword = keyword.trim();
            log.info("搜索检验项目，关键词={}", trimmedKeyword);

            QueryWrapper<Fmeditem> wrapper = new QueryWrapper<>();
            wrapper.like("ItemName", trimmedKeyword)
                    .ne("DelMark", 1)
                    .eq("RecordType", 2);

            List<Fmeditem> items = fmeditemService.list(wrapper);
            log.info("搜索检验项目成功，数量={}", items.size());
            return ResponseEntity.ok(items);
        } catch (Exception e) {
            log.error("搜索检验项目异常", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 提交检验申请
     */
    @PostMapping("/requests")
    public ResponseEntity<Void> submitTestRequest(@RequestBody TestRequestVO request) {
        try {
            if (request == null || request.getPatientId() == null ||
                    request.getDoctorId() == null || request.getItems() == null ||
                    request.getItems().isEmpty()) {
                log.warn("提交检验申请失败：参数无效");
                return ResponseEntity.badRequest().build();
            }

            log.info("处理检验申请，患者ID={}，项目数量={}", request.getPatientId(), request.getItems().size());

            for (TestRequestItem item : request.getItems()) {
                if (item.getItemId() == null) {
                    log.warn("项目ID为空，拒绝提交");
                    return ResponseEntity.badRequest().build();
                }

                Checkapply apply = new Checkapply();
                apply.setRegistid(request.getPatientId());
                apply.setDoctorid(request.getDoctorId());
                apply.setItemid(item.getItemId());
                apply.setName(getFmeditemNameSafely(item.getItemId()));
                apply.setObjective(request.getPurpose());
                apply.setIsurgent(item.getIsUrgent() ? 1 : 0);
                apply.setNum(1);
                apply.setCreationtime(new Date());
                apply.setState(0); // 0=未执行
                apply.setRecordtype(2);

                // 设置科室信息
                if (item.getDepartmentId() != null) {
                    apply.setDeptid(item.getDepartmentId());
                    apply.setDeptname(getDepartmentNameSafely(item.getDepartmentId()));
                }

                checkapplyService.save(apply);
            }

            log.info("检验申请提交成功");
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            log.error("提交检验申请异常", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 获取患者的检验申请列表（使用挂号ID查询）
     */
    @GetMapping("/patient/register/{registerId}")
    public ResponseEntity<List<Checkapply>> getPatientTestItems(@PathVariable Integer registerId) {
        try {
            if (registerId == null || registerId <= 0) {
                log.warn("获取检验申请失败：registerId无效");
                return ResponseEntity.badRequest().build();
            }

            log.info("获取挂号ID={}的检验申请", registerId);

            // 使用挂号ID(registid)查询患者的检验申请
            QueryWrapper<Checkapply> wrapper = new QueryWrapper<>();
            wrapper.eq("registid", registerId)
                    .eq("recordtype", 2); // 确保只查询检验申请

            List<Checkapply> testItems = checkapplyService.list(wrapper);

            // 补充项目价格信息（从Fmeditem获取）
            for (Checkapply item : testItems) {
                Fmeditem fmeditem = fmeditemService.getById(item.getItemid());
                if (fmeditem != null) {
                    item.setPrice(fmeditem.getPrice());
                }
            }

            log.info("获取挂号ID={}的检验申请成功，数量={}", registerId, testItems.size());
            return ResponseEntity.ok(testItems);
        } catch (Exception e) {
            log.error("获取检验申请异常", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // 辅助方法：安全获取项目名称
    private String getFmeditemNameSafely(Integer itemId) {
        if (itemId == null) return "未知项目";
        try {
            Fmeditem item = fmeditemService.getById(itemId);
            return item != null ? item.getItemname() : "未知项目";
        } catch (Exception e) {
            log.error("获取项目名称失败，ID={}", itemId, e);
            return "项目名称获取失败";
        }
    }

    // 辅助方法：安全获取科室名称
    private String getDepartmentNameSafely(Integer deptId) {
        try {
            if (deptId == null) return "未知科室";
            Department dept = departmentService.getById(deptId);
            return dept != null ? dept.getDeptname() : "未知科室";
        } catch (Exception e) {
            log.error("获取科室名称失败，ID={}", deptId, e);
            return "科室名称获取失败";
        }
    }

    // 内部类：检验申请参数VO
    public static class TestRequestVO {
        private Integer patientId;
        private Integer doctorId;
        private String purpose;
        private List<TestRequestItem> items;

        // getter和setter
        public Integer getPatientId() { return patientId; }
        public void setPatientId(Integer patientId) { this.patientId = patientId; }
        public Integer getDoctorId() { return doctorId; }
        public void setDoctorId(Integer doctorId) { this.doctorId = doctorId; }
        public String getPurpose() { return purpose; }
        public void setPurpose(String purpose) { this.purpose = purpose; }
        public List<TestRequestItem> getItems() { return items; }
        public void setItems(List<TestRequestItem> items) { this.items = items; }
    }

    public static class TestRequestItem {
        private Integer itemId;
        private Integer departmentId;
        private boolean isUrgent;

        // getter和setter
        public Integer getItemId() { return itemId; }
        public void setItemId(Integer itemId) { this.itemId = itemId; }
        public Integer getDepartmentId() { return departmentId; }
        public void setDepartmentId(Integer departmentId) { this.departmentId = departmentId; }
        public boolean getIsUrgent() { return isUrgent; }
        public void setIsUrgent(boolean urgent) { isUrgent = urgent; }
    }
}